package com.yundasys.lab02springbootstudy.future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.BiFunction;

/**
 * @PACKAGE_NAME: com.yundasys.lab02springbootstudy.future
 * @NAME: CompletableFuture3
 * @USER: jiangta
 * @DATE: 2021/12/9
 * @TIME: 8:08 上午
 * @PROJECT_NAME: springboot-labs
 */
public class CompletableFuture3 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        CompletableFuture.runAsync(()-> {}).thenRun(()->{});
        CompletableFuture.runAsync(()->{}).thenAccept(resultA -> {
            System.out.println("resultA=" + resultA);
        });
        CompletableFuture.runAsync(()->{}).thenApply(resultA -> "resultB");

        CompletableFuture.supplyAsync(()->"resultA").thenRun(() -> {

        });
        CompletableFuture.supplyAsync(()->"resultA").thenAccept(resultA -> {
            System.out.println("resultA:" + resultA);
        });

        CompletableFuture.supplyAsync(()->"resultA").thenApply((resultA) -> resultA + "resultB");

        CompletableFuture<String> future = CompletableFuture.supplyAsync(() ->{
            throw new RuntimeException();
        }).exceptionally(ex->"errorResultA")
                .thenApply(resultA -> resultA + " resultB")
                .thenApply(resultB -> resultB + " resultC")
                .thenApply(resultC -> resultC + " resultD");
        System.out.println(future.join());
        System.out.println(future.get());


        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> " resultA")
                .thenApply(resultA -> resultA + " resultB")
                .thenApply(resultB -> {throw new RuntimeException();})
                .handle(new BiFunction<Object, Throwable, Object>() {
                    @Override
                    public Object apply(Object o, Throwable throwable) {
                        if(throwable != null) {
                            return "errorResultC";
                        }
                        return o;
                    }
                })
                .thenApply(resultC -> resultC + " resultD");
        System.out.println(future1.join());
    }
}
